import logging, Image, ImageDraw, ImageFont
import cStringIO
import paste, random

from eshop.lib.base import *

log = logging.getLogger(__name__)

class CaptchaController(BaseController):
    
    def index(self):
        try:
            word = self.__generate_word()
            session['ESHOP_CAPTHCHA'] = word
            session.save()
            fapp = paste.fileapp.DataApp(self.__prepare_image(word))
            return fapp(request.environ, self.start_response)
        except Exception, e:
            log.warning(e)
            return 'Fail to generate captcha image'
            
    def view(self):
        return self.index()
    
    def __generate_word(self):
        s = ''
        for i in range(0, 4):
            s += random.choice('abcdefghijklmnoprstuvwxyz0123456789')
        return s
        
    def __prepare_image(self, word):
        img_width = 200
        img_height = 50
        img = Image.new('RGB', (img_width, img_height), '#353DFF')
        draw = ImageDraw.Draw(img)
        for i in range(0, 20):
            draw.line((random.uniform(0, img_width), random.uniform(0, img_height)) + (random.uniform(0, img_width), random.uniform(0, img_height)))
        font=ImageFont.truetype('arial.ttf', 48)
        draw.text((30, 0), word, font=font)
        stream = cStringIO.StringIO()
        img.save(stream, "png")
        return stream.getvalue()
        